<template>
  <div class="account-login">
    <el-form :model="form" :rules="rules" ref="formRef" class="login-form">
      <el-form-item prop="account">
        <ekInput
          v-model="form.account"
          placeholder="请输入账户"
          :clearable="true"
          style="width: 100%"
          @clear="clear"
          @keyup.enter="handleLogin"
        />
      </el-form-item>
      <el-form-item prop="password">
        <ekInput
          v-model="form.password"
          placeholder="请输入密码"
          :clearable="true"
          @clear="clear"
          style="width: 100%"
          :showPassword="true"
          @keyup.enter="handleLogin"
        />
      </el-form-item>
      <el-form-item
        prop="verify"
     
      >
        <div class="captcha-box">
          <ekInput
            v-model="form.verify"
            placeholder="请输入验证码"
            :clearable="true"
            @clear="clear"
            style="width: 100%"
            @keyup.enter="handleLogin"
          />
         
          <img :src="imageData" @click="doGetLoginGenerate" style="margin-left:20px;height:28px;" />
        </div>
      </el-form-item>
    </el-form>
    <el-button
      type="primary"
      size="large"
      @click="handleLogin"
      class="login-btn"
      :loading="loading"
      >登录</el-button
    >

    <el-dialog
      v-model="visiable"
      width="340"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <SliderCaptchas
        v-if="visiable"
        :width="configs.verify_config.width"
        :height="configs.verify_config.height"
        :tolerant="configs.verify_config.tolerant"
        :targetConfigX="targetConfigX"
        @success="sliderCaptchasSuccess"
        @refresh="sliderCaptchasRefresh"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import {
  defineComponent,
  onMounted,
  getCurrentInstance,
  reactive,
  ref,
} from "vue";
import { useStore } from "vuex";
import {
  login,
  getLoginGenerate,
  getLoginConfig as fetchLoginConfig,
  getSliderVerify as fetchSliderVerify,
} from "../api";
import { useRouter } from "vue-router";
import ekInput from "@/components/form/ekInput/index.vue";
import { setToken, setRefreshToken, logoutClear } from "@/utils/sys";
import { storage } from "@/utils/storage";
import NormalCaptchas from "@/components/business/ekCaptchas/normalCaptchas.vue";
import SliderCaptchas from "@/components/business/ekCaptchas/sliderCaptchas.vue";
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();
const { $storage, $http } = globalProperties;
const store = useStore();
const router = useRouter();

const clear = () => {
  console.log("clear");
};
const imageData = ref('');
const doGetLoginGenerate =()=> {
    getLoginGenerate().then((res)=>{
      if(res.status == 'success'){
         form.value.uuid = res.data.captcha_key;
         imageData.value = res.data.captcha_img;
      }
     
    })
}
onMounted(() => {
  // getLoginConfig();
doGetLoginGenerate();
});
let form = ref({
  account: "",
  password: "",
  verify: "",
  uuid:""
});
let rules = reactive({
  account: [{ required: true, message: "请输入账户", trigger: "blur" }],
  password: [{ required: true, message: "请选择密码", trigger: "blur" }],
});

const visiable = ref(false);
const loading = ref(false);
const targetConfigX = ref(0);

const formRef = ref(null);
const handleLogin = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (configs.value.verify && configs.value.verify_type === "slider") {
        targetConfigX.value = await getSliderVerify();
        visiable.value = true;
      } else {
        doLogin();
      }
    }
  });
};
const sliderCaptchasRefresh = async (done) => {
  targetConfigX.value = await getSliderVerify();
  done();
};
const getSliderVerify = async () => {
  let res = await fetchSliderVerify();
  if (res.status === "success") {
    return res.data.verify;
  }
  return "";
};
const sliderCaptchasSuccess = (code) => {
  form.value.verify = code;
  doLogin();
};
const doLogin = () => {
  loading.value = true;
  login(form.value)
    .then((res) => {
      setToken(res.data.token);
      setRefreshToken(res.data.refresh_token);
      let permission = res.data.node_data.map((item) => item.code);
      store.dispatch("permission/addPermission", permission);
      res.data.node_data.push({
          "id": 'R121212122121222',
          "module_code": null,
          "code": "FUNCTION_PERSON",
          "parent_id": 'R111111',
          "node_name": "个人中心",
          "node_icon": "",
          "node_router": "/person",
          "node_template": "/person/index",
          "node_url": "",
          "node_auth": "1",
          "node_cache": "0",
          "node_type": "3",
          "node_mode": "1",
          "node_depth": 3,
          "node_path": "108-109",
          "node_sort": 0,
          "ctime": "2025-07-24 22:34:34",
          "utime": "2025-07-24 22:42:12",
          "dtime": 0
      },{
          "id": 'R121212122121',
          "module_code": null,
          "code": "FUNCTION_TRANSFER_DETAILS",
          "parent_id": 'R1111',
          "node_name": "转运单详情",
          "node_icon": "",
          "node_router": "/transfer/detail",
          "node_template": "/transfer/detail",
          "node_url": "",
          "node_auth": "1",
          "node_cache": "0",
          "node_type": "3",
          "node_mode": "1",
          "node_depth": 3,
          "node_path": "108-109",
          "node_sort": 0,
          "ctime": "2025-07-24 22:34:34",
          "utime": "2025-07-24 22:42:12",
          "dtime": 0
      },
      {
          "id": 'R121212122122',
          "module_code": null,
          "code": "FUNCTION_ORDER_DETAILS",
          "parent_id": 'R1112',
          "node_name": "订单详情",
          "node_icon": "",
          "node_router": "/order/detail",
          "node_template": "/order/detail",
          "node_url": "",
          "node_auth": "1",
          "node_cache": "0",
          "node_type": "3",
          "node_mode": "1",
          "node_depth": 3,
          "node_path": "108-1099",
          "node_sort": 0,
          "ctime": "2025-07-24 22:34:34",
          "utime": "2025-07-24 22:42:12",
          "dtime": 0
      },{
          "id": 'R1212121221234',
          "module_code": null,
          "code": "FUNCTION_ALL_DETAILS",
          "parent_id": 'R11124',
          "node_name": "订单详情",
          "node_icon": "",
          "node_router": "/all/detail",
          "node_template": "/all/detail",
          "node_url": "",
          "node_auth": "1",
          "node_cache": "0",
          "node_type": "3",
          "node_mode": "1",
          "node_depth": 3,
          "node_path": "108-1099",
          "node_sort": 0,
          "ctime": "2025-07-24 22:34:34",
          "utime": "2025-07-24 22:42:12",
          "dtime": 0
      })
      store.dispatch("layout/setNodeData", res.data.node_data);
      // 动态注册路由
      if (res.data.node_data?.length) {
        // 添加路由
        store.dispatch("layout/addRoutes", res.data.node_data);
      }
      // 清除
      store.dispatch("layout/clear");
      // 初始化模块
      store.dispatch("layout/init");
      store.dispatch("permission/setUserInfo",res.data.manage_data);
      goHome();
    })
    .finally((err) => {
      loading.value = false;
      visiable.value = false;
    });
};

const goHome = () => {
  router.push("/");
};
const configs = ref({
  verify: true,
  verify_type: "normal",
  verify_config: {},
});
const getLoginConfig = () => {
  fetchLoginConfig().then((res) => {
    if (res.status === "success") {
      configs.value = {
        ...configs.value,
        ...res.data,
      };
    }
  });
};
</script>

<style scoped lang="scss">
.account-login {
    width: 300px;
  > .login-form {
    width: 100% ;
  }
  > .login-btn {
    width: 100% ;
  }
  .captcha-box {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .ek-captchas-normal {
      margin-left: 8px;
    }
  }
}
:deep(.el-dialog__body) {
  display: flex;
  justify-content: center;
}
</style>
